/**
 * 
 */
package paymentSystem;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TimedObject;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.jws.WebMethod;
import javax.jws.WebService;

import org.apache.commons.httpclient.NameValuePair;

/**
 * @author ASGroup0904
 */

@Stateless
@WebService
public class PaymentSystem implements TimedObject, PaymentSystemRemote {

	@Resource
	private TimerService timerService;

	@Resource
	private String paymentResponseURI;

	private Integer maxTime = new Integer(1000 * 30); // in ms

	private void createEspireTimer(Integer orderId) {
		timerService.createTimer(maxTime, orderId.intValue() + "");
	}

	@WebMethod
	public void paymentRedirect(Integer orderId) {
		System.out.print("PAYMENT SYSTEM; creato timer " + orderId);
		createEspireTimer(orderId);
	}

	@Timeout
	public void paymentVerify(Timer timer) {
		Integer orderId;

		Boolean status;
		System.out.print("payment verify: order id: ");
		orderId = Integer.parseInt(timer.getInfo().toString());
		System.out.print("payment verify: order id: " + orderId);

		status = false;
		System.out.print("payment success" + status + " " + orderId);
		try {
			Http.post(paymentResponseURI, new NameValuePair("payd", status
					.toString()), new NameValuePair("orderId", orderId
					.toString()));
			System.out.print("SCADENZA TIMER PAGAMENTO");
		} catch (Exception e) {
			System.out.println("PaymentSystem: pagina non trovata, riprovo");
			createEspireTimer(orderId);
			return;
		} finally {
			timer.cancel();
		}
	}

	// return 0: ok; -1:pagina non trovata; -2: timer non trovato, pagamento
	// arrivato troppo tardi
	@WebMethod
	public int doPayment(Integer orderId) {
		System.out.print("payment success ok " + orderId);
		Object[] timerArray = timerService.getTimers().toArray();
		Timer timer = null;
		System.out.print("numero timer " + timerArray.length);
		for (int i = 0; i < timerArray.length; i++) {
			timer = (Timer) timerArray[i];
			System.out.print("timer " + timer.getInfo());
			System.out.print("timer order id input " + orderId.toString());
			if (timer.getInfo().toString().equalsIgnoreCase(orderId.toString())) { // timer
																					// tovato
				Boolean status = true;
				try {
					Http.post(paymentResponseURI, new NameValuePair("payd",
							status.toString()), new NameValuePair("orderId",
							orderId.toString()));
					System.out.print("PAGAMENTO");
				} catch (Exception e) {
					System.out.println("PaymentSystem: pagina non trovata");
					return -1;
				} finally {
					timer.cancel();
				}
				return 0;
			}
		}
		return -2;
	}

	@Override
	public void ejbTimeout(Timer arg0) {
		// TODO Auto-generated method stub

	}

}
